using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SmartAgricultureService.Core;
using SmartAgricultureService.Models.Tables;

namespace SmartAgricultureService.Controllers
{
    [Authorize]
    [ApiController]
    [Route("api/[controller]")]
    public class ReportController(DatabaseContext database, IHttpContextAccessor httpContextAccessor) : ControllerBase(httpContextAccessor)
    {
        [HttpGet("getDeviceData")]
        public async Task<IActionResult> GetDeviceData(string deviceId, DateTime dateTime)
        {
            try
            {
                var deviceEntry = await database.Devices.Include(o => o.Area).AsNoTracking().FirstOrDefaultAsync(x => x.Id == deviceId && !x.Delete && x.Active);
                if (deviceEntry == null)
                    return Reject("不存在该设备");
                else if (!await database.IsMatchArea(deviceEntry.Area.Code))
                    return Reject("设备不在指定的区域内，无法获取！");
                var viewReports = await database.ReportDetails.Include(o => o.Report).Where(rd => rd.Report != null && rd.DeviceId == deviceId && rd.Report.ReportDate.Date == dateTime).GroupBy(rd => rd.Hour)
                    .Select(grouped => new ViewReport
                    {
                        Hour = grouped.Key,
                        AvgTemperature = grouped.Average(g => g.AvgTemperature),
                        MinTemperature = grouped.Min(g => g.MinTemperature),
                        MaxTemperature = grouped.Max(g => g.MaxTemperature),
                        AvgHumidity = grouped.Average(g => g.AvgHumidity),
                        MinHumidity = grouped.Min(g => g.MinHumidity),
                        MaxHumidity = grouped.Max(g => g.MaxHumidity),
                        AvgIllumination = grouped.Average(g => g.AvgIllumination),
                        MinIllumination = grouped.Min(g => g.MinIllumination),
                        MaxIllumination = grouped.Max(g => g.MaxIllumination)
                    }).ToListAsync();
                return Success(viewReports);
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
        }
        [HttpGet("getAreaData")]
        public async Task<IActionResult> GetAreaData(string areaCode, DateTime dateTime)
        {
            try
            {
                var deviceEntry = await database.Devices.Include(o => o.Area).AsNoTracking().FirstOrDefaultAsync(x => x.Area != null && x.Area.Code == areaCode && !x.Delete && x.Active);
                if (deviceEntry == null)
                    return Reject("不存在该设备");
                else if (!await database.IsMatchArea(deviceEntry.Area.Code))
                    return Reject("设备不在指定的区域内，无法获取！");
                else
                {
                    var viewReports = await database.ReportDetails.Include(o => o.Report).Where(rd => rd.Report != null && rd.Report.ReportDate.Date == dateTime && rd.Report.AreaCode == areaCode).GroupBy(rd => rd.Hour)
                            .Select(grouped => new ViewReport
                            {
                                Hour = grouped.Key,
                                AvgTemperature = grouped.Average(g => g.AvgTemperature),
                                MinTemperature = grouped.Min(g => g.MinTemperature),
                                MaxTemperature = grouped.Max(g => g.MaxTemperature),
                                AvgHumidity = grouped.Average(g => g.AvgHumidity),
                                MinHumidity = grouped.Min(g => g.MinHumidity),
                                MaxHumidity = grouped.Max(g => g.MaxHumidity),
                                AvgIllumination = grouped.Average(g => g.AvgIllumination),
                                MinIllumination = grouped.Min(g => g.MinIllumination),
                                MaxIllumination = grouped.Max(g => g.MaxIllumination)
                            }).ToListAsync();
                    return Success(viewReports);
                }
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
        }
        [HttpGet("getDeviceWeekData")]
        public async Task<IActionResult> GetDeviceWeekData(string deviceId, DateTime dateTime)
        {
            try
            {
                var deviceEntry = await database.Devices.Include(o => o.Area).AsNoTracking().FirstOrDefaultAsync(x => x.Id == deviceId && !x.Delete && x.Active);
                if (deviceEntry == null)
                    return Reject("不存在该设备");
                else if (!await database.IsMatchArea(deviceEntry.Area.Code))
                    return Reject("设备不在指定的区域内，无法获取！");
                else
                {
                    var viewReports = await (from rd in database.ReportDetails
                                             join r in database.Reports on rd.ReportId equals r.Id
                                             where rd.DeviceId == deviceId
                                             where r.ReportDate >= dateTime.AddDays(-7).Date && r.ReportDate <= dateTime.Date
                                             group rd by r.ReportDate.Date
                        into grouped
                                             select new ViewReport
                                             {
                                                 Day = grouped.Key,
                                                 AvgTemperature = grouped.Average(g => g.AvgTemperature),
                                                 MinTemperature = grouped.Min(g => g.MinTemperature),
                                                 MaxTemperature = grouped.Max(g => g.MaxTemperature),
                                                 AvgHumidity = grouped.Average(g => g.AvgHumidity),
                                                 MinHumidity = grouped.Min(g => g.MinHumidity),
                                                 MaxHumidity = grouped.Max(g => g.MaxHumidity),
                                                 AvgIllumination = grouped.Average(g => g.AvgIllumination),
                                                 MinIllumination = grouped.Min(g => g.MinIllumination),
                                                 MaxIllumination = grouped.Max(g => g.MaxIllumination)
                                             }).AsNoTracking().ToListAsync();
                    return Success(viewReports);
                }
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
        }
        [HttpGet("getAreaWeekData")]
        public async Task<IActionResult> GetAreaWeekData(string areaCode, DateTime dateTime)
        {
            try
            {
                if (!await database.IsMatchArea(areaCode))
                    return Reject("设备不在指定的区域内，无法获取！");
                else
                {
                    var viewReports = await (from rd in database.ReportDetails
                                             join r in database.Reports on rd.ReportId equals r.Id
                                             where r.AreaCode == areaCode
                                             where r.ReportDate >= dateTime.AddDays(-7).Date && r.ReportDate <= dateTime.Date
                                             group rd by r.ReportDate.Date
                    into grouped
                                             select new ViewReport
                                             {
                                                 Day = grouped.Key,
                                                 AvgTemperature = grouped.Average(g => g.AvgTemperature),
                                                 MinTemperature = grouped.Min(g => g.MinTemperature),
                                                 MaxTemperature = grouped.Max(g => g.MaxTemperature),
                                                 AvgHumidity = grouped.Average(g => g.AvgHumidity),
                                                 MinHumidity = grouped.Min(g => g.MinHumidity),
                                                 MaxHumidity = grouped.Max(g => g.MaxHumidity),
                                                 AvgIllumination = grouped.Average(g => g.AvgIllumination),
                                                 MinIllumination = grouped.Min(g => g.MinIllumination),
                                                 MaxIllumination = grouped.Max(g => g.MaxIllumination)
                                             }).AsNoTracking().ToListAsync();
                    return Success(viewReports);
                }
            }
            catch (Exception ex)
            {
                return Error(ex);
            }
        }
    }
}